package lazy2.util;

import java.io.IOException;
import java.io.Reader;

public class CharacterReader {
	static final char EOF = (char)-1;
	final int BUFFER_LENGTH = 512;
	char[] buffer = new char[BUFFER_LENGTH];
	int index   = 0;
	int len     = 0;
	int readLen = 0;
	char c;
	Reader reader;
	
	public CharacterReader(Reader reader) {this.reader = reader;}
	
	private char _readNext() throws IOException {
		if(index<readLen) return c=buffer[index++];
		if(len>=0) len = reader.read(buffer);
		switch (len) {
		case -1:
			close();
		case -2:
			return EOF;
		default:
			index = 0;
			readLen = len;
			return c=buffer[index++];
		}
	}
	public final void close() {
		if(len!=-2 && reader!=null) {
			try {
				reader.close();
			} catch (IOException e) {}
			len = -2;
		}
	}
	public char readNext() throws IOException {
		try {
			return _readNext();
		} catch (IOException e) {
			close();
			throw e;
		}
	}
	public void readBack() {if(index>0) --index;}
}
